// ==UserScript==
// @name         GGMR - 全局GitHub镜像重定向工具：高效、灵活、易用 (Global GitHub Mirror Redirector)
// @namespace    https://gitee.com/AningMicroHoard/Global-GitHub-Mirror-Redirector/
// @version      1.2
// @description  全局GitHub镜像重定向工具（可配置镜像地址）| 镜像站安全警告显示
// @author       Aning
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // ===================== 配置区域 =====================
    const MIRROR_DOMAIN = 'kkgithub.com'; // 国内推荐镜像：https://fcp7.com/github-mirror-daily-updates.html
    // ===================================================

    // 镜像站安全警告逻辑
    if (window.location.hostname === MIRROR_DOMAIN) {
        // 创建警告条
        const warningBar = document.createElement('div');
        warningBar.innerHTML = '<strong>安全警告：</strong>请勿在镜像站登录！可能导致账号泄露！';

        // 样式配置
        warningBar.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: #dc3545;
            color: white;
            padding: 12px 20px;
            text-align: center;
            z-index: 2147483647;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            font-size: 14px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        `;

        // 添加图标
        warningBar.insertAdjacentHTML('afterbegin', '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L3 21h18L12 2zm0 6v6m0 2v-2"/></svg>');

        // 插入到页面顶部
        document.documentElement.prepend(warningBar);

        // 动态调整页面布局
        const adjustLayout = () => {
            const barHeight = warningBar.offsetHeight;
            document.body.style.marginTop = `${barHeight}px`;
            document.body.style.scrollMarginTop = `${barHeight}px`; // 处理锚点定位
        };

        // 初始调整
        adjustLayout();

        // 监听窗口变化
        window.addEventListener('resize', adjustLayout);

        // 不执行后续脚本
        return;
    }


    // 自动重定向GitHub请求
    const shouldRedirect = window.location.host.match(/\.?github\.com$/i);
    if (shouldRedirect) {
        const newUrl = window.location.href.replace(
            /(https?:\/\/)([a-z0-9-]+\.)*github\.com/gi,
            `$1${MIRROR_DOMAIN}`
        );
        if (newUrl !== window.location.href) {
            window.location.replace(newUrl);
            return;
        }
    }

    // 创建动态正则表达式
    const createGitHubRegex = (prefix = '') => {
        const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        return new RegExp(`${escaped}github\\.com`, 'gi');
    };

    // 增强型替换逻辑
    const replaceGitHubLinks = (content) => {
        return content
            // 处理标准URL
            .replace(createGitHubRegex('(https?://)'), `$1${MIRROR_DOMAIN}`)
            // 处理WebSocket
            .replace(createGitHubRegex('(wss?://)'), `$1${MIRROR_DOMAIN}`)
            // 处理相对路径
            .replace(/(["'])\/\/github\.com/gi, `$1//${MIRROR_DOMAIN}`)
            // 处理SSH地址
            .replace(/(git@)github\.com/gi, `$1${MIRROR_DOMAIN}`)
            // 处理子模块引用
            .replace(/(\/github\.com)/gi, `/${MIRROR_DOMAIN}`);
    };

    // DOM处理器
    const processNode = (node) => {
        // 处理文本节点
        if (node.nodeType === Node.TEXT_NODE) {
            const newContent = replaceGitHubLinks(node.textContent);
            if (newContent !== node.textContent) {
                node.textContent = newContent;
            }
        }
        // 处理元素节点
        else if (node.nodeType === Node.ELEMENT_NODE) {
            // 处理属性
            const attributes = ['href', 'src', 'action', 'data-src', 'cite', 'formaction'];
            attributes.forEach(attr => {
                const value = node.getAttribute(attr);
                if (value) {
                    const newValue = replaceGitHubLinks(value);
                    if (newValue !== value) {
                        node.setAttribute(attr, newValue);
                    }
                }
            });

            // 特殊处理框架内容
            if (node.tagName === 'IFRAME' && node.contentDocument) {
                processDOM(node.contentDocument);
            }
        }
    };

    // 递归遍历DOM
    const processDOM = (root) => {
        processNode(root);
        let child = root.firstChild;
        while (child) {
            processDOM(child);
            child = child.nextSibling;
        }
    };

    // 初始处理
    processDOM(document);

    // 动态内容监听
    new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            mutation.addedNodes.forEach(node => {
                if (node.nodeType === Node.ELEMENT_NODE) {
                    processDOM(node);
                }
            });
        });
    }).observe(document, {
        childList: true,
        subtree: true
    });

    // 拦截AJAX请求
    const interceptXHR = () => {
        const originalOpen = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function(method, url) {
            arguments[1] = replaceGitHubLinks(url);
            return originalOpen.apply(this, arguments);
        };
    };

    const interceptFetch = () => {
        const originalFetch = window.fetch;
        window.fetch = function(input, init) {
            if (typeof input === 'string') {
                input = replaceGitHubLinks(input);
            } else if (input instanceof Request) {
                input = new Request(replaceGitHubLinks(input.url), input);
            }
            return originalFetch(input, init);
        };
    };

    interceptXHR();
    interceptFetch();
})();